package cn.com.bluemoon.daps.sync.core.sync.log;

import cn.com.bluemoon.daps.common.enums.SyncToEnv;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 日志记录工具类
 * 1. 打印到日志文件
 * 2. 记录下来，方便后续存储起来
 */
@Slf4j
public final class LogUtils {

    private static final ConcurrentHashMap<String, String> logCache = new ConcurrentHashMap<>();

    private LogUtils() {
    }

    /**
     * 生成发布同步业务key
     */
    public static String generateBizKey(String modelId, String taskId, SyncToEnv syncToEnv) {
        return String.join("-", modelId, taskId, syncToEnv.getCode() + "");
    }

    public static void main(String[] args) {
        String key = "test";
        int i = 0;
        logAndSet(key, log, "开始执行%s", i++, ":", new Date());
        logAndSet(key, log, "开始执行%s", i++, ":", new Date());
        logAndSet(key, log, "开始执行%s", i++, ":", new Date());
        logAndSet(key, log, "开始执行%s", i++, ":", new Date());
        logAndSet(key, log, "开始执行%s", i++, ":", new Date());
        System.out.println(getLogByKey(key));
        System.out.println();
    }

    /**
     * 缓存追加格式化日志信息
     */
    public static void logAndSet(@NotNull String key, Logger log, String msg, Object... param) {
        if (key == null) {
            return;
        }
        log.info(msg, param);
        synchronized (logCache) {
            if (logCache.containsKey(key)) {
                String pre = logCache.get(key);
                StringBuilder sb = new StringBuilder();
                sb.append(pre);
                sb.append("\r\n");
                sb.append(formatStr(msg, param));
                logCache.put(key, sb.toString());
            } else {
                logCache.put(key, formatStr(msg, param));
            }
        }
    }

    public static String formatStr(String msg, Object... param) {
        return new StringBuilder().append(DateUtil.formatDateTime(new Date())).append(" ").append("[")
                .append(Thread.currentThread().getName())
                .append("-")
                .append(Thread.currentThread().getId())
                .append("]")
                .append(" ").append(String.format(msg, param) != null ? String.format(msg, param) : "").toString();
    }

    public static String getThenClearByKey(@NotNull String key) {
        if (key == null) {
            return "";
        }
        return logCache.remove(key);
    }

    public static String getLogByKey(@NotNull String key) {
        if (key == null) {
            return "";
        }
        return logCache.getOrDefault(key, "");
    }

    public static void clearByKey(@NotNull String key){
        if (key == null) {
            return;
        }
        logCache.remove(key);
    }

    public static void clearAll(){
        logCache.clear();
    }
}
